import { BasePromiseResultType } from '#/request'
import { RequestStatus } from '@/enums/request'
import { getPlatformInfo } from '@/utils/platform'
const useResponseInterceptor = {
  successHooks: (res: any): Promise<any> => {
    if (res.data.code === RequestStatus.SUCCESS) {
      return Promise.resolve(res)
    }
    return Promise.resolve(false)
  },
  errorHooks: (res: any): Promise<any> => Promise.reject(false),
}
console.log(getPlatformInfo().baseUrl, '222222222222222222222222222')
const useRequestInterceptor = (method: string, url: string, params: any, data: any, header?: any, responesData?: any): any => {
  const requestData: any = {
    url: getPlatformInfo().baseUrl + url,
    method,
    data: params || data,
    timeout: 6000,
    header: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/json',
      ...header,
    },
  }

  if (responesData) {
    Object.keys(responesData).forEach((item) => (requestData[item] = responesData[item]))
  }
  //   if(){
  // requestData.header.Authorization = 'I am token'
  //   }
  return requestData
}

export const getRequest = <T>(method: string, url: string, params: any, data: any, header?: any, responesData?: any): Promise<BasePromiseResultType<T>> => {
  return new Promise((resolve) => {
    uni.request({
      ...useRequestInterceptor(method, url, params, data, header, responesData),
      success: async (res: any) => {
        console.log(res, '========返回数据==========')
        const result = await useResponseInterceptor.successHooks(res)
        if (result) {
          resolve([result.data, null])
        } else {
          resolve([null, res.msg || res.data.msg])
        }
      },
      fail: async (err: any) => {
        const result = useResponseInterceptor.errorHooks(err)
        resolve([null, err.message])
      },
    })
  })
}
